package com.kotodama.domain.valueobjects;

import jakarta.persistence.Embeddable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.regex.Pattern;

/**
 * 邮箱值对象
 * 封装邮箱地址的验证逻辑
 */
@Embeddable
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class Email {

    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");

    private String value;

    public Email(String value) {
        validateEmail(value);
        this.value = value.toLowerCase().trim();
    }

    /**
     * 验证邮箱格式
     * 
     * @param email 邮箱地址
     * @throws IllegalArgumentException 如果邮箱格式无效
     */
    private void validateEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱地址不能为空");
        }

        String trimmedEmail = email.trim();

        if (trimmedEmail.length() > 254) {
            throw new IllegalArgumentException("邮箱地址长度不能超过254个字符");
        }

        if (!EMAIL_PATTERN.matcher(trimmedEmail).matches()) {
            throw new IllegalArgumentException("邮箱地址格式无效: " + trimmedEmail);
        }
    }

    /**
     * 获取邮箱的域名部分
     * 
     * @return 域名
     */
    public String getDomain() {
        return value.substring(value.indexOf('@') + 1);
    }

    /**
     * 获取邮箱的用户名部分
     * 
     * @return 用户名
     */
    public String getLocalPart() {
        return value.substring(0, value.indexOf('@'));
    }

    @Override
    public String toString() {
        return value;
    }
}